import { PLUGIN_ID } from '../config';
import setLayoutAndViewportData from './setLayoutAndViewportData.js';

export default function setMPRLayout(
  displaySet,
  detailsArray,
  numRows = 1,
  numColumns = 1,
  mode = 'mpr'
) {
  return new Promise((resolve, reject) => {
    const viewports = [];
    // const numViewports = numRows * numColumns;
    const numViewports = 3;

    if (detailsArray && detailsArray.length !== numViewports) {
      reject(
        new Error(
          'viewportProps is supplied but its length is not equal to numViewports'
        )
      );
    }

    const viewportSpecificData = {};
    const plugin = mode === 'mpr' ? PLUGIN_ID : '';

    for (let i = 0; i < numViewports; i++) {
      viewports.push({});
      viewportSpecificData[i] = displaySet;
      viewportSpecificData[i].plugin = plugin;
    }

    const apis = [];
    viewports.forEach((viewport, index) => {
      apis[index] = null;
      viewports[index] = Object.assign({}, viewports[index], {
        plugin,
        details: {
          ...detailsArray[index],
          mode,
          afterCreation: api => {
            apis[index] = api;
            if (apis.every(a => !!a)) {
              resolve(apis);
            }
          },
        },
      });
    });

    setLayoutAndViewportData(
      {
        numRows,
        numColumns,
        viewports,
      },
      viewportSpecificData
    );
  });
}
